import React from "react";
import BaseField from "./BaseField";
import {sleepFunc} from "jh-utils";

export default class BaseInputField extends BaseField {

    /**
     * 标识“值是否有变化”
     * @type {boolean}
     */
    valueChanged = false;

    componentWillUnmount() {
        super.componentWillUnmount && super.componentWillUnmount();
        // 如果是在单元格中使用，那么组件卸载之前，触发 afterCbs
        if (this.props.cell) {
            this.runAfterCbs(this.getValue());
        }
    }

    hdlValueFocus(e) {
        this.doingFocus = true;
        this.setState({focusing: true});
        this.runPropsFunc('onFocus')(e);
    }

    hdlValueBlur(e) {
        // 每次失去焦点的时候，触发 afterCbs
        this.runAfterCbs(this.getValue());
        this.setState({focusing: false});
        this.runPropsFunc('onBlur')(e, this.getValue());
    }

    /**
     * 用于传入 Input 或 InputNumber 的 ref 属性，实现“聚焦后，全选输入框的内容”功能
     * @param ref
     */
    refFunc(ref) {
        if (ref && ref.input && this.doingFocus) {
            if (ref.input.select) {
                this.doingFocus = false;
                sleepFunc(0).then(() => {
                    ref && ref.input && ref.input.select();
                })
            }
        }
    }

    _changeFunc(value) {
        this.valueChanged = true;
        this.runPropsFunc('onChange')(value, false);
        // this.runAfterCbs(value); // 在 onChange 事件，不触发 afterCbs，在失焦之后才触发
    }

    runAfterCbs(value) {
        if (this.valueChanged) {
            this.valueChanged = false;
            this.runPropsFunc('onChange')(value);
            super.runAfterCbs(value);
        }
    }
}